//全局配置初始化
;(function(window){
    //ajax全局设置
    $.ajaxSetup({
        cache: false,//取消浏览器缓存
        complete:function(xhr,status){//session过期判断
            if(status=="parsererror"){//json解析失败的错误
                window.open("login", target="_top");
                //layer.msg("parsererror");
            } else if(xhr.status==504){
                layer.alert("请求超时，请稍后再试！");
            } else if(status=="error"){
                layer.alert("请求异常，请稍后再试！");
            }
        }
    });
	//layui
    layer.config({
        extend: 'extend/layer.ext.js'
    });

})(window);
//工具初始化
;(function(win){
	var pwin = win.parent;
    var $p = win.Public = {};
    $p._version = "v1.0.0";
    //tab 操作
    $p._tab = win.Tab||pwin.Tab || {};
    $p._message = win.Message||pwin.Message || {};
    $p._tab.bindCtrl = function(){
    	var _this = this;
        if(this.M && pwin!=win){
            $("#tab_refresh_btn").on("click",function(){
                _this.M.reload(_this.M.getSelectedTabItemID());
            });
            $("#tab_close_others_btn").on("click",function(){
                _this.M.removeOther(_this.M.getSelectedTabItemID());
            });
            $("#tab_close_all_btn").on("click",function(){
                _this.M.removeAll(_this.M.getSelectedTabItemID());
            });
        }
	};
    $p._tab.bindCtrl();


    //grid 表格
    $p._grid = {
        setSize:function($grid) {
            var gw = $grid.closest(".ui-jqgrid").parent().innerWidth();
            $grid.jqGrid("setGridWidth",gw - 5);
        },
        autoSize:function($grid){
            var _this = this ;
            _this.setSize($grid);
            $(window).resize(function(){
                _this.setSize($grid);
            });
        }
	};
	//上传下载
    $p._upload = {

	};
    //窗口操作
    $p._win =  {
        gridBigHeight:function(){
            return $(win).height()-$(".grid-wrapper").offset().top-200;
        },
		gridBigOpenHeight:function(){
            return $(win).height()*0.8+"px";
        },gridBigOpenWidth:function(){
            return $(win).width()*0.8+"px";
        }
    }

	win.Public = $p;
    win.pwin = pwin;
})(window);


//-- zhang zhen fu 2020-12-14 start
//通用校验
window.commonRegular = {
    //数量校验
    isInteger:{
        //支持 8 位非负整数
        "8":function(value){
            var reg =  /^\d{0,8}$/;
            return reg.test(value);
        },
        //支持 8 位整数
        "*8":function(value){
            var reg =  /^-?\d{0,8}$/;
            return reg.test(value);
        }
    },
    //价格校验
    isPrice:{
        //支持 8 位非负整数和 2 位小数
        "8_2":function(value){
            var reg = /^((\d{0,8})|(\d{0,8}\.\d{0,2}))$/;
            return reg.test(value);
        },
        //支持 8 位非负整数和 4 位小数
        "8_4":function(value){
            var reg = /^((\d{0,8})|(\d{0,8}\.\d{0,4}))$/;
            return reg.test(value);
        }

    },
    //金额校验
    isAmount:{
        //支持 8 位非负整数和 2 位小数
        "8_2":function(value){
            var reg = /^((\d{0,8})|(\d{0,8}\.\d{0,2}))$/;
            return reg.test(value);
        },
        //支持 8 位非负整数和 3 位小数
        "8_3":function(value){
            var reg = /^((\d{0,8})|(\d{0,8}\.\d{0,3}))$/;
            return reg.test(value);
        },
        //支持 8 位非负整数和 4 位小数
        "8_4":function(value){
            var reg = /^((\d{0,8})|(\d{0,8}\.\d{0,4}))$/;
            return reg.test(value);
        },
        //支持 8 位整数和 2 位小数
        "*8_2":function(value){
            var reg = /^((-?\d{0,8})|(-?\d{0,8}\.\d{0,2}))$/;
            return reg.test(value);
        },
        //支持 8 位整数和 3 位小数
        "*8_3":function(value){
            var reg = /^((-?\d{0,8})|(-?\d{0,8}\.\d{0,3}))$/;
            return reg.test(value);
        },
        //支持 8 位整数和 4 位小数
        "*8_4":function(value){
            var reg = /^((-?\d{0,8})|(-?\d{0,8}\.\d{0,4}))$/;
            return reg.test(value);
        }
    },
    //比率校验
    isRate:{
        //支持 3 位非负整数和 2 位小数
        "3_2":function (value) {
            var reg = /^((\d{0,3})|(\d{0,3}\.\d{0,2}))$/;
            return reg.test(value);
        },
        //支持 3 位整数和 2 位小数
        "*3_2":function (value) {
            var reg = /^((-?\d{0,3})|(-?\d{0,3}\.\d{0,2}))$/;
            return reg.test(value);
        }
    }
};
//组件生成器
window.ComponentBuilder = {
    //通用客户端表格
    "clientGrid":function(){
        return new ComponentBuilder.f.ClientGrid();
    },
    //下拉多选框
    "selectpicker":function(param){
        var selector = param.selector;
        var url = param.url;
        var emptyText = param.empty?param.empty.text:"请选择";
        $("#"+selector).on("show.bs.select",function(){
            var $selectWrapper = $(this).closest(".bootstrap-select");
            $selectWrapper.find(".dropdown-menu.open").css({"max-height":"309px","overflow":"hidden"});
            $selectWrapper.find(".dropdown-menu.inner").css({"max-height":"260px","overflow-y":"auto"});
        }).on("loaded.bs.select",function(){
            var $select = $(this),$keyword = $select.closest(".bootstrap-select").find("input"),keyword = "",timeout = null;
            $keyword.on("input propertychange",function(){
                var options = "";
                clearTimeout(timeout);
                timeout = setTimeout(function(){
                    if($keyword.val().length>0&&$keyword.val()!=keyword){
                        keyword = $keyword.val();
                        $.post(url,{"keyword":$keyword.val()},function(data){
                            if(data&&data.length>0){
                                options += "<option value=''>"+emptyText+"</option>";
                                $.each(data,function(i){
                                    options += "<option value='"+data[i].value+"'>"+data[i].label+"</option>";
                                });
                            } else {
                                options = "<option value=''>"+emptyText+"</option>";
                            }
                            $select.html(options);
                            $select.selectpicker("refresh");
                        });
                    }
                },500);
            });
        });
    },
    /*
	树形选择框
	<div class="form-group">
		<label>商品类别：</label>
		<input type="text" id="goods_category_name" class="form-control w150" readonly="readonly">
		<input type="hidden" id="goods_category_value" name="params[goodsCategoryId]">
	</div>
     .......
	 <div id="goods_category_tree_wrapper" class="ztree_select" style="background-color:#fff;">
        <ul id="goods_category_tree" class="ztree" style="margin-top:0;max-height:200px;overflow:auto"></ul>
    </div>

    传入的 name 为 goods_category ，以此类推
    verify:用于节点点击事件的校验，不填则不校验。若有，则必须有返回值（true|false）
    "selecttree":function(name,url,verify)
    var param = {name,url,verify,callback,show:{direction:'top'}};
	 */
    "selecttree":function(param){
        var name=param.name,url=param.url,verify=param.verify;
        var curNode;
        var categoryTree = $.fn.zTree.init($("#"+name+"_tree"), {
            view: {
                dblClickExpand: false
            },
            async: {
                enable: true,
                url:url,
                autoParam: ["id"],
                // dataFilter: function(treeId, parentNode, childNodes) {
                //     if (!childNodes) return null;
                //     for (var i=0, l=childNodes.length; i<l; i++) {
                //         childNodes[i].isParent = true;
                //     }
                //     return childNodes;
                // }
            },
            data : {
                simpleData : {
                    enable : true,
                    idKey : "id",
                    pIdKey : "parentId"
                }
            },
            callback: {
                onClick: function(e, treeId, treeNode) {
                    //节点校验
                    if(verify){
                        if(!verify(treeNode)){
                            return;
                        }
                    }
                    if(treeNode==curNode) {
                        categoryTree.cancelSelectedNode(treeNode);
                        curNode = null;
                        $("#"+ name +"_name").val("");
                        $("#"+ name +"_value").val("");
                    } else {
                        curNode = treeNode;
                        $("#"+ name +"_name").val(treeNode.name);
                        $("#"+ name +"_value").val(treeNode.id);
                    }
                    if(param.click){
                        //点击回调
                        param.click(treeNode);
                    }
                    hideAreaSelect();
                }
            }
        });
        function showAreaSelect() {
            var area = $("#"+name+"_name");
            var areaOffset = $("#"+name+"_name").offset();
            if(param.show && param.show.direction =='top'){
                $("#"+name+"_tree_wrapper").css({left:areaOffset.left + "px", top:areaOffset.top -140 + "px",width:area.outerWidth(),height:"140px",overflow:"auto"}).slideDown("fast");
                $("#"+name+"_tree").css({overflow:"unset"});
            }else{
                $("#"+name+"_tree_wrapper").css({left:areaOffset.left + "px", top:areaOffset.top + area.outerHeight() + "px",width:area.outerWidth()}).slideDown("fast");
            }
            $("body").bind("mousedown", onBodyDown);
        }
        function hideAreaSelect() {
            $("#"+name+"_tree_wrapper").fadeOut("fast");
            $("body").unbind("mousedown", onBodyDown);
        }
        function onBodyDown(event) {
            if (!(event.target.id == (name+"_tree_wrapper") || $(event.target).parents("#"+name+"_tree_wrapper").length>0)) {
                hideAreaSelect();
            }
        }

        $("#"+name+"_name").on("click",showAreaSelect);
    },
};
//组件构建器中的扩展对象
window.ComponentBuilder.f = {};
//通用客户端表格扩展
ComponentBuilder.f.ClientGrid = function(){};
ComponentBuilder.f.ClientGrid.prototype = (function(window){
    var _prototype = {
        id:"grid",
        grid:undefined,//渲染后的表格对象
        maxRowNum:null,//最大行数
        currentEditRow:{rowId:undefined,iCol:undefined,iRow:undefined},
        //表格数据校验字典
        validate:{},
        //创建表格，定义参数
        createGrid:function(){},
        //行表单校验
        rowCheck:function(data,field){return true},
        //表格表单校验
        gridSubmit:function(required){return null},
        //获取表单数据
        getGridData:function(){return null},
    };
    /**
     * 表单渲染,id,createGrid 必填
     * @param option 表单渲染参数，例如：{id:"table1",createGrid:function(){.....}}
     */
    _prototype.render = function(option){
        $.extend(true, this, option);
        var _this = this;
        //初始化表格
        var grid = _this.createGrid();

        _this.grid = grid ;
    };
    /**
     * 新增行
     * @param $btn 当前新增按钮
     */
    _prototype.addGridRow = function($btn) {
        var _this = this;
        var grid = _this.grid,currentEditRow = _this.currentEditRow;
        grid.jqGrid("saveCell",currentEditRow.iRow,currentEditRow.iCol);
        if(_this.maxRowNum){
            if($("tbody tr",grid).length>_this.maxRowNum){
                layer.msg("当前表格最多" + _this.maxRowNum + "行");
                return;
            }
        }
        var rowid = $btn.data("id");
        grid.jqGrid("addRowData",$.jgrid.randId(),{},"after",rowid);
    };
    /**
     * 移除行
     * @param $btn 当前删除按钮
     */
    _prototype.removeGridRow = function($btn){
        var _this = this;
        var grid = _this.grid,currentEditRow = _this.currentEditRow;
        var rowid = $btn.data("id");
        if($("tbody tr",grid).length>2){
            grid.jqGrid("saveCell",currentEditRow.iRow,currentEditRow.iCol);
            grid.jqGrid("delRowData",rowid);
        }
        grid.jqGrid("resetSelection");
    };

    _prototype.recordCurrentEditRow = function(options){
        var _this = this;
        _this.currentEditRow = {rowId:options['rowId'],iCol:options['iCol'],iRow:options['iRow']};
    };
    /**
     * 保存单元格
     */
    _prototype.saveCell = function(){
        var _this = this;
        var grid = _this.grid,currentEditRow = _this.currentEditRow;
        if( currentEditRow.iRow&&currentEditRow.iCol){
            grid.jqGrid("saveCell",currentEditRow.iRow,currentEditRow.iCol);
        }
    };
    /**
     * 行数据校验
     * @param required 是否必填
     * @param data 检验的行数据
     * @param field 校验字段名称
     * @returns {boolean} 是否校验成功
     */
    _prototype.rowCheck = function(required,data,field){
        var flag = true ;
        var _this = this;
        if(field){
            var val = data[key];
            if(required||(val!=undefined&&val!=null&&val!='')){
                //字段必填或者有数据才做校验
                flag = _this.validate[field](val);
            }
        }else{
            for(var key in _this.validate){
                var val = data[key];
                if(val!=undefined&&val!=null&&val!=''){
                    //如果本行需要校验的字段有数据，则改成需要校验
                    required = true;
                    break;
                }
            }
            for(var key in _this.validate){
                var val = data[key];
                if(required||(val!=undefined&&val!=null&&val!='')){
                    flag = _this.validate[key](val);
                    if(!flag){
                        break;
                    }
                }
            }
        }
        return flag ;
    };
    /**
     * 数据表格提交校验
     * @param required 是否必填
     * @returns {boolean} 是否校验成功
     */
    _prototype.gridSubmit = function(required){
        var _this = this;
        var grid = _this.grid;
        var allData = grid.jqGrid("getRowData");
        var flag = true ;//默认成功
        if(required&&allData.length==0){
            //必填&表格为空
            layer.msg("请填写表格数据");
            return false;
        }
        for(var i=0;i<allData.length;i++){
            var data = allData[i];
            flag = _this.rowCheck(required,data)
            if(!flag){
                break;
            }
        }
        return flag ;
    };

    /**
     * 获取数据
     * 如果行全部数据都为空，则不返回
     * @returns {any[]} 表格数据
     */
    _prototype.getGridData = function(){
        var _this = this;
        var grid = _this.grid;
        var allData = grid.jqGrid("getRowData");
        var data = new Array();
        for(var i=0;i<allData.length;i++){
            var d = allData[i];
            delete d.actions;
            var flag = false;//默认不添加到数据
            for(var key in d){
                if(d[key]){
                    //只要有一个值不为空，则都要放到数据
                    flag = true;
                }
            }
            if(flag){
                data.push(d);
            }
        }
        return data;
    };
    /**
     * 回填数据到表格
     * @param data 表格数据
     */
    _prototype.setGridData = function(data){
        var _this = this;
        if(data&&data.length>0){
            _this.grid.jqGrid("clearGridData");
            for(var i=0;i<data.length;i++){
                _this.grid.jqGrid("addRowData",$.jgrid.randId(),data[i]);
            }
        }
    };
    return _prototype;
})(window);

